<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class Admin_Model_HtaccessMapper{
    public function RefreshUrl($list) {
		$file = '.htaccess';
		$f = fopen ( $file, 'r+' );
		$contents = fread ( $f, filesize ( $file ) );
		$p1 = strpos ( $contents, '#<list>' );
		$p2 = strpos ( $contents, '#</list>' );
		$result = array ('success' => false, 'msg' => 'Неизвестная ошибка' );
		if ($p1 == false)
			$result = array ('success' => false, 'msg' => 'В файле не установлен #<list>' );
		elseif ($p2 == false)
			$result = array ('success' => false, 'msg' => 'В файле не установлен #</list>' );
		else {
            $result = array ('success' => true, 'msg' => 'Список URL обновлен успешно' );
			//$list = $this->mapper->fetchURLs ();
			$newcnt = "#<list>\n";
			foreach ( $list as $l ) {
                if (!preg_match('/^[a-zA-Z0-9\-\/\.\(\)\+\=\~\?\&\%]+$/',$l['URL'])){
                   $result['success'] = false;
                   $result['msg'] = 'Не все адреса добавлены. Не добавлен: '.$l['URL'];
                   continue;
                }
				$u = ($l['URL']{0}=='/') ? substr($l['URL'],1) : $l['URL'];
				$u = str_replace('(', '\(', $u);
				$u = str_replace(')', '\)', $u);
				$u = str_replace('+', '\+', $u);
				$p = strpos($u,'#',0);
				if ($p!==false)
					$u = substr($u,0,$p);
				
				//$newcnt .= 'RewriteRule ^' . $u . '/$ index.php?Id=' . $l ['Id'] . " [NC,L]\n";
				$newcnt .= 'RewriteRule ^' . $u . '$ index.php?Id=' . $l ['Id'] . " [NC,L]\n";
			}
			$newcnt .= "#</list>";
			$newcnt = substr ( $contents, 0, $p1 ) . $newcnt;
			$newcnt .= substr ( $contents, $p2 + 8 );
			fseek ( $f, 0 );
			fwrite ( $f, $newcnt );
			ftruncate ( $f, strlen ( $newcnt ) );
		}
		fclose ( $f );
		return $result;
	}
}
?>
